#include <iostream>
#include <cstdlib>
#include <pthread.h>

#include "classes/tcp/xsocket.h"

using namespace std;

const int RCVBUFSIZE = 32;

void HandleTCPClient(TCPSocket *sock);		// TCP client handling function
void *ThreadMain(void *clientSocket);		// Main program of a thread

/*
 * Program entry point.
 */
int main(int argc, char *argv[])
{
	unsigned short port = 1338;

	try {
		// Create the server socket
		TCPServerSocket serverSocket(port);

		// Main loop
		while(1) {
			// Create seperate memory for client argument
			TCPSocket *clientSocket = serverSocket.accept();

			// Create client thread
			pthread_t threadID;
			if (pthread_create(&threadID, NULL, ThreadMain, (void *) clientSocket) != 0) {
				cerr << "Unable to create thread." << endl;
				exit(1);
			}
		}
	} catch (SocketException &e) {
		cerr << e.what() << endl;
		exit (1);
	}

	return 0;
}

/*
 * TCP Client handling function.
 */
void HandleTCPClient(TCPSocket *sock)
{
	// Receive information and echo it back
	char echoBuffer[RCVBUFSIZE];
	int rcvSize;
	while ((rcvSize = sock->recv(echoBuffer, RCVBUFSIZE)) > 0) { // 0 means end of transmission
		//string msg = "Bericht ontvangen!!\n\n";
		const char msg[] = "Bericht ontvangen!!\n\n";

		// Echo it back
		sock->send(msg, 21);
	}
	cout << endl << endl << "--End of transmission--" << endl << endl;
}

/*
 * Socket receive entry point.
 */
void *ThreadMain(void *clientSocket)
{
	// Deallocate the thread
	pthread_detach(pthread_self());
	cout << endl << "Client accepted" << endl;

	// Extract socket descriptor from the argument
	HandleTCPClient((TCPSocket *)clientSocket);
	cout << endl << "Client disconnected" << endl;

	// Deallocate the socket
	delete (TCPSocket *)clientSocket;
	return NULL;
}
